package com.example.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.jline.terminal.Terminal;
import org.jline.utils.InfoCmp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.shell.standard.ShellCommandGroup;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;
import org.springframework.shell.standard.commands.Clear;
import org.springframework.shell.standard.commands.History;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
@ShellComponent
@ShellCommandGroup("system ctl")
public class HistoryCommand implements History.Command{

    private final org.jline.reader.History jLineHistory;

    public HistoryCommand(org.jline.reader.History jLineHistory) {
        this.jLineHistory = jLineHistory;
    }

    @ShellMethod(value = "Display or save the history of previously run commands")
    public List<String> history(@ShellOption(help = "A file to save history to.", defaultValue = ShellOption.NULL) File file) throws IOException {
        if (file == null) {
            List<String> result = new ArrayList<>(jLineHistory.size());
            jLineHistory.forEach(e -> result.add(e.line()));
            return result;
        } else {
            try (FileWriter w = new FileWriter(file)) {
                for (org.jline.reader.History.Entry entry : jLineHistory) {
                    w.append(entry.line()).append(System.lineSeparator());
                }
            }
            return Collections.singletonList(String.format("Wrote %d entries to %s", jLineHistory.size(), file));
        }
    }

}



